public class 边界着色 {

    public int[][] queue = new int[2501][2];
    public int l,r;
    public int[] moves = {-1,0,1,0,-1};
    public int[][] colorBorder(int[][] grid, int row, int col, int color) {
        int n = grid.length;
        int m = grid[0].length;
        int[][] ans = new int[n][m];
        boolean[][] vis = new boolean[n][m];
        l = r = 0;
        queue[r][0] = row;
        queue[r++][1] = col;
        while (l < r) {
            int[] t = queue[l++];
            int a = t[0];
            int b = t[1];
            int cnt = 0;
            for (int i = 0;i < 4;i++) {
                int x = t[0] + moves[i];
                int y = t[1] + moves[i + 1];
                if (x < 0 || x >= n || y < 0 || y >= m) continue; // 超出边界值
                if (grid[x][y] != grid[a][b]) continue; // 颜色不同
                cnt++; // 颜色相同
                if (vis[x][y]) continue;
                queue[r][0] = x;
                queue[r++][1] = y;
                vis[x][y] = true;
            }

            ans[a][b] = cnt == 4 ? grid[a][b] : color;
        }
        for (int i = 0;i < n;i++) {
            for (int j = 0;j < m;j++) {
                if (ans[i][j] == 0) {
                    ans[i][j] = grid[i][j];
                }
            }
        }
        return ans;
    }
}
